package com.itcast.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.reggie.commen.CustomException;
import com.itcast.reggie.pojo.R;
import com.itcast.reggie.pojo.User;
import com.itcast.reggie.Dto.UserDto;
import com.itcast.reggie.service.UserService;
import com.itcast.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RestController
@Slf4j
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserService userService;
    //发送验证码
    @PostMapping("/sendMsg")
    public R sendMsg(HttpSession session ,@RequestBody User user){
        //判断数据库里面有没有这个号码,没有就注册进数据库
        /*String phone = user.getPhone();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User localUser = userService.getOne(wrapper);
        if(localUser == null){
            userService.save(user);
        }*/
        //获取随机码,存入session
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        System.out.println("-----------------------");
        System.out.println("-----------------------");
        System.out.println("验证码是"+code);
        System.out.println("-----------------------");
        System.out.println("-----------------------");
        session.setAttribute("Code",code);
        return R.success("生成验证码成功");
    }

    //登录验证
   @PostMapping("/login")
    public R<String> login(HttpSession session, @RequestBody UserDto userDto){
        //判断验证码对不对
       String localCode = (String) session.getAttribute("Code");
       String Usercode = userDto.getCode();
       if(!Usercode.equals(localCode)){
           throw new CustomException("验证码错误");
       }
       //判断电话号码对不对
       String phone = userDto.getPhone();
       QueryWrapper<User> wrapper = new QueryWrapper<>();
       wrapper.eq("phone", phone);
       User localUser = userService.getOne(wrapper);
       if(localUser == null){
           throw new CustomException("用户不存在");
       }
       session.removeAttribute("Code");
       session.setAttribute("UserId", localUser.getId());
       return R.success("登录成功");
   }

   //退出
   @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
       session.removeAttribute("UserId");
       return R.success("success");
   }
}
